let form = layui.form;
let id = new URLSearchParams(location.search).get('id');
// console.log(id);

// 获取分类，渲染到下拉框的位置
$.ajax({
    url: '/my/category/list',
    success: function(res) {
        let arr = [];
        res.data.forEach(item => {
            arr.push(`<option value="${item.id}">${item.name}</option>`)
        });
        $('select[name=cate_id]').append(arr.join(''));
        // 更新渲染
        form.render('select');
        // 获取一篇文章，进行数据回填 
        $.ajax({
            url: '/my/article/' + id,
            success: function(res) {
                console.log(res)
                    // 数据回填
                form.val('edit', res.data);
                initEditor();
                // 单独回填图片
                image.cropper('destroy').attr('src', baseUrl + '/' + res.data.cover_img).cropper(option);
            }
        });
    }
});



// 实现基础的剪裁效果
let image = $('#image');
let option = {
    aspectRatio: 400 / 280,
    preview: '.img-preview',
    autoCropArea: 1
};
image.cropper(option);

// 点击 选择封面 按钮，触发文件域的单击事件
$('button:contains("选择封面")').on('click', function() {
    $('#file').trigger('click');
});

// 当文件域的内容change之后，能够更换剪裁区的图片
$('#file').on('change', function() {
    // 获取文件列表
    let files = this.files;
    if (files.length > 0) {
        let url = URL.createObjectURL(files[0]);
        image.cropper('destroy').attr('src', url).cropper(option);
    }
});



$('form').on('submit', function(e) {
    e.preventDefault();
    let fd = new FormData(this);

    fd.set('content', tinyMCE.activeEditor.getContent());
    // 剪裁图片
    let canvas = image.cropper('getCroppedCanvas', { width: 400, height: 280 });
    canvas.toBlob(blob => {
        fd.append('cover_img', blob);
        fd.append('id', id);


        $.ajax({
            type: 'POST',
            url: '/my/article/update',
            data: fd,
            processData: false,
            contentType: false,
            success: function(res) {
                if (res.status === 0) {
                    layer.msg(res.message, { time: 1000 }, function() {
                        location.href = './list.html';
                    });
                } else {
                    layer.msg(res.message);
                }
            }
        });
    });
})